<template>
  <j-modal
    :width='modalWidth'
    :visible='visible'
    :title='title'
    switchFullscreen
    @ok='handleSubmit'
    @cancel='close'
    style='top:50px'
    cancelText='关闭'
  >
    <a-tabs :active-key='activeKey' @tabClick='tabClick'>
      <a-tab-pane key='1' tab='负责人'>
        <SelectPosition ref='SelectPosition' :current-data.sync='positionsData' :visible='visible' />
      </a-tab-pane>
    </a-tabs>

  </j-modal>
</template>

<script>
import { filterObj } from '@/utils/util'
import { queryDepartTreeList, getUserList, queryUserByDepId } from '@/api/api'
import { getAction, postAction } from '@/api/manage'
import JInput from '@/components/cn-form/JInput.vue'
import SelectPosition from '@/components/cn-components/select-position'
import { PageListMixin } from '@/mixins/PageListMixin'

export default {
  name: 'white-modal',
  components: { JInput, SelectPosition },
  props: ['modalWidth', 'multi', 'userIds'],
  data() {
    return {
      typeLoading: false,
      queryParam: {
        code: '',
        name: ''
      },
      positionsData: [],
      treeData: [],
      categoryData: [],
      categoryColumns: [
        {
          title: '分类编号',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '分类名称',
          align: 'center',
          dataIndex: 'name'
        }
      ],
      products: [],
      productData: [],
      productColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品图片',
          align: 'center',
          dataIndex: 'imgUrl',
          width: 80,
          ellipsis: true,
          scopedSlots: { customRender: 'imgUrl' }
        },
        {
          title: '商品编号',
          align: 'center',
          width: 120,
          ellipsis: true,
          dataIndex: 'code'
        },
        {
          title: '商品名称',
          align: 'center',
          width: 120,
          ellipsis: true,
          dataIndex: 'name'
        },
        // {
        //     title: '状态',
        //     align: 'center',
        //     dataIndex: 'status',
        //     width: 80,
        //     ellipsis: true,
        //     scopedSlots: {customRender: 'status'},
        // },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          width: 80,
          ellipsis: true,
          scopedSlots: { customRender: 'action' }
        }
      ],
      scrollTrigger: {},
      selectedRowKeys: [],
      selectUserRows: [],
      selectUserIds: [],
      title: '门店配置',
      selectedKeys: [],
      visible: false,
      form: this.$form.createForm(this),
      loading: false,
      expandedKeys: [],
      reqCode: '',
      activeKey: '1',
      url: {
        list: window._CONFIG['domianURL'] + '/cnProductController/getProductListByCust',
        selected: window._CONFIG['domianURL'] + '/cnTerminalController/getCnTerminalByIdOrTerminalCode'
      },
      record: null
    }
  },
  mixins: [PageListMixin],
  computed: {
    // 计算属性的 getter
    getType: function() {
      return this.multi == true ? 'checkbox' : 'radio'
    }
  },
  watch: {
    visible(v) {
      if (v) {
        this.$nextTick(() => {

          if (this.activeKey == '1') {
            this.queryDepartTree()
          } else if (this.activeKey == '2') {
            this.loadData()
          } else if (this.activeKey == '3') {
            if (this.$refs.SelectPosition) this.$refs.SelectPosition.loadData(1)
          }
        })
      }
    },
    activeKey() {
      if (this.activeKey == '1') {
        this.queryDepartTree()
      } else if (this.activeKey == '2') {
        this.loadData()
      } else if (this.activeKey == '3') {
        if (this.$refs.SelectPosition) this.$refs.SelectPosition.loadData(1)
      }
    }
    // reqCode() {
    //     if (this.reqCode != undefined && this.reqCode!='' ){
    //       this.getSelectdData()
    //     }
    // }
  },
  created() {
    // 该方法触发屏幕自适应
    this.resetScreenSize()
  },
  methods: {


    /**
     * 获取已选中数据
     */
    getSelectdData() {
      getAction(this.url.selected, { terminalCode: this.reqCode }).then(res => {
        const { result } = res
        this.record = result
        if (result && result.extendVos && result.extendVos.length) {
          // 1:与经销商关系 2:标签，3，与商品类型关系，4与商品关系

          const productType = result.extendVos.filter(row => Number(row.dataType) === 3)
          const products = result.extendVos.filter(row => Number(row.dataType) === 4)
          const positions = result.extendVos.filter(row => Number(row.dataType) === 5)
          this.positionsData = positions.map(position => Object.assign(position, {
            positionCode: position.code,
            positionName: position.name
          }))
          this.selectedKeys = productType.map(type => type.code)
          this.categoryData = productType
          this.productData = products
          this.positionsData = positions

          this.selectedRowKeys = products.map(row => row.code)
          this.selectionRows = products.map(product => Object.assign({
            code: product.code,
            name: product.name,
            status: product.status,
            imgUrl: product.remarks,
            id: product.id
          }))
        } else {
          this.selectedKeys = []
          this.categoryData = []
          this.productData = []
          this.positionsData = []

          this.selectedRowKeys = []
          this.selectionRows = []
        }
      })
    },

    /**
     * 删除已选中商品
     * @param record
     */
    handleDelete(record) {
      this.productData.remove(record)
      this.selectionRows.remove(record)
      this.selectedRowKeys.remove(record['code'])
    },
    /**
     * 标签页的选中事件
     * @param name
     */
    tabClick(name) {
      this.activeKey = name
    },
    /**
     * 递归树结构数据，取出所有子元素
     * @param children
     * @param selected
     * @returns {*}
     */
    getAllChildren(children, selected) {
      if (children && children.length) {
        children.map(child => {
          selected.push(child)
          this.getAllChildren(child.children, selected)
        })
      }
      return selected
    },
    /**
     * 选中树节点操作
     * @param checkedKeys
     * @param checked 不等于undefined 表示当前事件为checkbox事件，否则为点击树节点事件
     * @param checkedNodes
     * @param node
     * @param event
     */
    handleCheckbox(checkedKeys, { checked, checkedNodes, node, event }) {
      if (checked !== undefined) {
        //todo 当事件为checkbox事件时，checkedKeys当前选中的数据包含自节点数据
        this.selectedKeys = checkedKeys
        this.categoryData = this.getAllChildren(this.treeData, []).filter(node => checkedKeys.includes(node.code)).map(node =>
          Object.assign({}, node, {
            children: null
          }))
      } else {
        //todo 当事件为nodeClick事件时，checkedKeys当前选中数据为当前点击节点
        const checkNodes = [node.dataRef, ...this.getAllChildren(node.dataRef.children, [])]
        //todo 如果当前点击节点已经被选中，则执行删除操作
        if (this.selectedKeys.includes(node.dataRef.code)) {
          checkNodes.map(node => {
            this.selectedKeys.remove(node.code)
            //todo 从右边table删除选中数据
            this.categoryData.remove(node)
          })
        } else {
          this.selectedKeys = Array.from(new Set(this.selectedKeys.concat(checkNodes.map(node => node.code))))
          //todo 添加选中数据到右边table
          this.categoryData = Array.from(new Set([...this.categoryData, ...checkNodes.map(node => Object.assign({}, node, {
            children: null
          }))]))
        }

      }
    },
    /**
     * 覆盖mixin的loadData方法
     * @param arg
     * @returns {Promise<void>}
     */
    async loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()//查询条件
      await postAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.products = res.result.records.map(product => Object.assign({
            code: product.productCode,
            name: product.productName,
            status: product.status,
            dataType: 4,
            imgUrl: product.imgUrl,
            id: product.id
          }))
          this.ipagination.total = res.result.total
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    showModal(reqCode) {
      this.visible = true
      this.reqCode = reqCode
      this.form.resetFields()
      if (this.reqCode != undefined && this.reqCode != '') {
        this.getSelectdData()
      }
    },
    /**
     * 获取查询参数
     * @returns {*}
     */
    getQueryParams() {
      let param = Object.assign({}, this.queryParam)
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      return filterObj(param)
    },
    searchReset(num) {
      let that = this
      if (num !== 0) {
        that.loadData(1)
      }
      that.selectedRowKeys = []
      that.selectionRows = []
      that.selectedKeys = []
      that.productData = []
      that.categoryData = []
    },
    close() {
      this.searchReset(0)
      this.visible = false
      this.positionsData = []
      this.products = []
      this.treeData = []
    },
    handleSubmit() {
      let that = this
      that.$emit('ok', that.categoryData, that.productData, this.positionsData, this.record)
    },
    /**
     * 手动全选/取消全选分类
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    onSelectAll(selected, selectedRows, changeRows) {
      this.selectedRowKeys = selectedRows.map(row => row.code)
      this.selectionRows = selectedRows
      if (selected) {
        //todo 选中
        changeRows.map(row => {
          this.productData.push(row)
        })
      } else {
        //todo 取消选中
        changeRows.map(row => {
          this.productData.remove(row)
        })
      }
    },

    /**
     * 手动勾选/取消分类
     * @param record
     * @param selected
     * @param selectedRows
     * @param nativeEvent
     */
    onSelect(record, selected, selectedRows, nativeEvent) {
      this.selectedRowKeys = selectedRows.map(row => row.code)
      this.selectionRows = selectedRows
      if (selected) {
        //todo 选中
        this.productData.push(record)
      } else {
        //todo 取消选中
        this.productData.remove(record)
      }


    },
    onSearch() {
      this.loadData(1)
    },

    /**
     * 获取分类树
     * @returns {*}
     */
    queryDepartTree() {
      this.typeLoading = true
      return postAction(window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/findPageList').then((res) => {
        if (res.success) {
          this.treeData = this.handleStruct(res.result)
          // 默认展开父节点
          this.expandedKeys = this.treeData.map(item => item.code)
        }

        this.typeLoading = false
      }).catch(e => {
        this.$message.warning(res.message)
        this.typeLoading = false
      })
    },
    /**
     * 重构树结构数据
     * @param tree
     * @returns {*}
     */
    handleStruct(tree) {
      return tree.map(t => {
        const json = {
          code: t.typeCode,
          name: t.typeName,
          // status: t.status,
          dataType: 3,
          id: t.id,
          children: t.children
        }
        if (json.children) {
          json.children = this.handleStruct(json.children)
        }
        return json
      })
    },
    modalFormOk() {
      this.loadData()
    }
  }
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

#components-layout-demo-custom-trigger .trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color .3s;
}
</style>
